package com.iptv.live.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iptv.common.utils.poi.ExcelUtil;
import com.iptv.live.domain.LivePreviewTable;
import com.iptv.live.domain.dto.LiveExportDTO;
import com.iptv.live.domain.dto.LivePreviewTableAddDTO;
import com.iptv.live.domain.dto.LivePreviewTableEditDTO;
import com.iptv.live.domain.qo.LivePreviewTableQO;
import com.iptv.live.domain.vo.LiveListVo;
import com.iptv.live.service.ILivePreviewTableService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.iptv.common.annotation.Log;
import com.iptv.common.core.controller.BaseController;
import com.iptv.common.core.domain.AjaxResult;
import com.iptv.common.enums.BusinessType;
import com.iptv.common.core.page.TableDataInfo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 直播频道Controller
 * 
 * @author Cinzia
 * @date 2025-01-03
 */
@RestController
@RequestMapping("/live")
public class LivePreviewTableController extends BaseController
{
    private static final String SECRET_KEY = "Tp25076786"; // 应该是保密的密钥
    private static final long TIME_TOLERANCE = TimeUnit.MINUTES.toMillis(5); // Token有效时间

    @Autowired
    private ILivePreviewTableService livePreviewTableService;

    /**
     * 查询直播频道列表
     */
    @GetMapping("/list")
    public TableDataInfo list(LivePreviewTableQO livePreviewTableQo)
    {
        startPage();
        List<LivePreviewTable> list = livePreviewTableService.selectLivePreviewTableList(livePreviewTableQo);
        return getDataTable(list);
    }

    /**
     * 获取直播频道详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(livePreviewTableService.selectLivePreviewTableById(id));
    }

    /**
     * 新增直播频道
     */
    @Log(title = "直播频道", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LivePreviewTableAddDTO livePreviewTableAddDTO)
    {
        return toAjax(livePreviewTableService.insertLivePreviewTable(livePreviewTableAddDTO));
    }

    /**
     * 修改直播频道
     */
    @Log(title = "直播频道", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LivePreviewTableEditDTO livePreviewTableEditDTO)
    {
        return toAjax(livePreviewTableService.updateLivePreviewTable(livePreviewTableEditDTO));
    }

    /**
     * 删除直播频道
     */
    @Log(title = "直播频道", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(livePreviewTableService.deleteLivePreviewTableByIds(ids));
    }

    /**
     * 根据直播ID查询分类
     */
    @GetMapping("/getLiveType/{id}")
    public AjaxResult getLiveType(@PathVariable Long id)
    {
        return success(livePreviewTableService.getLiveType(id));
    }

    /**
     * 返回app节目列表
     */
    @GetMapping("/getLiveList")
    public AjaxResult getLiveList(){

        // 验证token
        if (!verifyToken()) {
            return AjaxResult.error("Invalid Token");
        }

        List<LiveListVo> liveList = livePreviewTableService.getLiveList();
        return AjaxResult.success(liveList);
    }

    /**
     * 生成token + timestamp
     * @return
     */
    @GetMapping("/generateToken")
    public AjaxResult generateToken(){
        // 获取当前时间戳（毫秒）
        String timestamp = String.valueOf(System.currentTimeMillis());

        // 生成 Token
        String token = generateToken(SECRET_KEY, timestamp);

        // 将生成的 Token 和 Timestamp 返回给客户端
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        result.put("timestamp", timestamp);

        return AjaxResult.success(result);
    }

    private boolean verifyToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("Token");
        String timestamp = request.getHeader("Timestamp");

        if (token == null || timestamp == null) {
            return false;
        }

        long requestTime = Long.parseLong(timestamp);
        long currentTime = System.currentTimeMillis();

        if (Math.abs(currentTime - requestTime) > TIME_TOLERANCE) {
            return false; // 时间戳超出有效期
        }

        String expectedToken = generateToken(SECRET_KEY, timestamp);
        return token.equals(expectedToken);
    }

    private String generateToken(String secretKey, String timestamp) {
        String rawStr = timestamp + secretKey;
        return md5Hex(rawStr);
    }

    private String md5Hex(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(data.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    @Log(title = "直播频道", businessType = BusinessType.INSERT)
    @PostMapping("/import/{type}")
    public AjaxResult add(@PathVariable String type,@RequestBody List<LiveExportDTO> liveExportDTOList)
    {
        livePreviewTableService.importLive(type,liveExportDTOList);
        return AjaxResult.success();
    }
}
